package com.towerfense;

import java.awt.Color;

import javax.swing.JLayeredPane;

@SuppressWarnings("serial")
public class FenseCanvas extends JLayeredPane {
	private GridTile tiles[][];
	private GridSelectionManager selectionManager;
	
	private static final int GRID_WIDTH = 10;
	private static final int GRID_HEIGHT = 20;
	
	public FenseCanvas() {
		setOpaque(true);
		setLayout(null);
//		setBackground(new Color(32, 32, 32));
		setBackground(Color.BLACK);
		
		selectionManager = new GridSelectionManager();
		
		initGrid();
	}
	
	private void initGrid() {
		tiles = new GridTile[GRID_HEIGHT][GRID_WIDTH];
		int l = 128;
		int h = 64;
		
		for(int i=0; i<GRID_HEIGHT; i++) {
			for(int j=0; j<GRID_WIDTH; j++) {
				tiles[i][j] = new GridTile(this, j, i);
				if(i%2 == 0)
					tiles[i][j].setLocation(j*l, i/2*h);
				else
					tiles[i][j].setLocation(j*l + l/2, i/2*h + h/2);
				add(tiles[i][j]);
			}
		}
		
		for(int i=0; i<GRID_HEIGHT; i++) {
			for(int j=0; j<GRID_WIDTH; j++) {
				if(i%2 == 0) {
					if(i != 0) {
						tiles[i][j].east = tiles[i-1][j];
						if(j != 0)
							tiles[i][j].north = tiles[i-1][j-1];
					}
					if(i < GRID_HEIGHT-1) {
						tiles[i][j].south = tiles[i+1][j];
						if(j != 0)
							tiles[i][j].west = tiles[i+1][j-1];
					}
				} else {
					tiles[i][j].north = tiles[i-1][j];
					if(j < GRID_WIDTH-1)
						tiles[i][j].east = tiles[i-1][j+1];
					
					if(i < GRID_HEIGHT-1) {
						tiles[i][j].west = tiles[i+1][j];
						if(j < GRID_WIDTH-1)
							tiles[i][j].south = tiles[i+1][j+1];
					}
				}
			}
		}
	}
	
	void zoomIn() {
		int l;
		int h;
		for(int i=0; i<GRID_HEIGHT; i++) {
			for(int j=0; j<GRID_WIDTH; j++) {
				tiles[i][j].zoomIn();
				l = tiles[i][j].getWidth();
				h = tiles[i][j].getHeight();
				if(i%2 == 0)
					tiles[i][j].setLocation(j*l, i/2*h);
				else
					tiles[i][j].setLocation(j*l + l/2, i/2*h + h/2);
			}
		}
		repaint();
	}
	
	void zoomOut() {
		int l = tiles[0][0].getWidth();
		int h = tiles[0][0].getHeight();
		for(int i=0; i<GRID_HEIGHT; i++) {
			for(int j=0; j<GRID_WIDTH; j++) {
				tiles[i][j].zoomOut();
				l = tiles[i][j].getWidth();
				h = tiles[i][j].getHeight();
				
				if(i%2 == 0)
					tiles[i][j].setLocation(j*l, i/2*h);
				else
					tiles[i][j].setLocation(j*l + l/2, i/2*h + h/2);
			}
		}
		repaint();
	}
	
	void hover(GridTile tile) {
		if(selectionManager.hover(tile))
			repaint();
	}
	
	void select(GridTile tile) {
		selectionManager.select(tile);
	}

//	public void paintComponent(Graphics _g) {
//		Graphics2D g = (Graphics2D)_g;
//	}
}
